// 消息中心页面
Page({
  data: {
    messages: [],
    unreadCount: 0,
    tabs: ['全部', '未读', '系统通知', '考试提醒'],
    activeTab: 0,
    loading: true
  },
  
  onLoad: function() {
    this.getMessages();
  },
  
  onShow: function() {
    // 每次页面显示时刷新消息
    this.getMessages();
  },
  
  onPullDownRefresh: function() {
    this.getMessages(() => {
      wx.stopPullDownRefresh();
    });
  },
  
  // 获取消息列表
  getMessages: function(callback) {
    this.setData({ loading: true });
    
    // 获取应用实例以获取服务器地址
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    // 确保有用户ID
    let userId = null;
    if (userInfo) {
      // 尝试多种可能的ID字段
      userId = userInfo.userId || userInfo.id;
    }
    
    if (!userId) {
      console.error('用户未登录或缺少userId');
      this.setData({ 
        loading: false,
        messages: []
      });
      if (callback) callback();
      return;
    }
    
    // 构建查询参数
    let queryParams = { userId: userId };
    
    // 根据当前选中的标签筛选消息
    if (this.data.activeTab === 1) {
      // 未读消息
      queryParams.isRead = false;
    } else if (this.data.activeTab === 2) {
      // 系统通知
      queryParams.type = 'system';
    } else if (this.data.activeTab === 3) {
      // 考试提醒
      queryParams.type = 'exam_reminder';
    }
    
    wx.request({
      url: `${serverUrl}/api/messages`,
      method: 'GET',
      data: queryParams,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('获取消息成功:', res.data);
          this.setData({
            messages: res.data,
            loading: false
          });
          
          // 计算未读消息数量
          const unreadCount = res.data.filter(msg => !msg.isRead).length;
          this.setData({ unreadCount });
        } else {
          console.error('获取消息失败:', res);
          this.setData({ 
            loading: false,
            messages: []
          });
        }
        
        if (callback) callback();
      },
      fail: (err) => {
        console.error('获取消息请求失败:', err);
        
        // 使用模拟数据
        const mockMessages = [
          {
            id: 1,
            title: '系统通知',
            content: '欢迎使用智慧校园系统',
            sendTime: '2023-12-15 10:30',
            isRead: true,
            type: 'system'
          },
          {
            id: 2,
            title: '考试提醒',
            content: '您有一场高等数学考试将于明天上午9:00开始',
            sendTime: '2023-12-14 15:20',
            isRead: false,
            type: 'exam_reminder',
            relatedId: 101
          },
          {
            id: 3,
            title: '请假审批通知',
            content: '您的请假申请已被批准',
            sendTime: '2023-12-13 09:15',
            isRead: false,
            type: 'notice'
          }
        ];
        
        this.setData({
          messages: mockMessages,
          loading: false,
          unreadCount: mockMessages.filter(msg => !msg.isRead).length
        });
        
        if (callback) callback();
      }
    });
  },
  
  // 切换标签
  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index
    });
    this.getMessages();
  },
  
  // 查看消息详情
  viewMessage: function(e) {
    const messageId = e.currentTarget.dataset.id;
    const message = this.data.messages.find(msg => msg.id === messageId);
    
    if (!message) {
      wx.showToast({
        title: '消息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 标记为已读
    if (!message.isRead) {
      // 获取应用实例以获取服务器地址
      const app = getApp();
      const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
      const token = wx.getStorageSync('token');
      
      wx.request({
        url: `${serverUrl}/api/messages/${messageId}/read`,
        method: 'PUT',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.statusCode === 200) {
            console.log('标记消息已读成功');
            
            // 更新本地消息状态
            const messages = this.data.messages.map(msg => {
              if (msg.id === messageId) {
                msg.isRead = true;
              }
              return msg;
            });
            
            const unreadCount = this.data.unreadCount - 1;
            this.setData({ 
              messages,
              unreadCount: unreadCount > 0 ? unreadCount : 0
            });
          }
        }
      });
    }
    
    // 根据消息类型执行不同操作
    if (message.type === 'exam_reminder' && message.relatedId) {
      // 跳转到考试详情
      wx.navigateTo({
        url: `/pages/student/kaoshi/detail/detail?id=${message.relatedId}`
      });
    } else if (message.type === 'notice' && message.relatedId) {
      // 跳转到通知详情
      wx.navigateTo({
        url: `/pages/student/notice/detail/detail?id=${message.relatedId}`
      });
    } else {
      // 普通消息，显示详情
      wx.navigateTo({
        url: `/pages/common/messages/detail/detail?id=${messageId}`
      });
    }
  },
  
  // 标记全部已读
  markAllRead: function() {
    wx.showLoading({ title: '处理中' });
    
    // 获取应用实例以获取服务器地址
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    // 确保有用户ID
    let userId = null;
    if (userInfo) {
      userId = userInfo.userId || userInfo.id;
    }
    
    if (!userId) {
      wx.hideLoading();
      wx.showToast({ 
        title: '用户未登录', 
        icon: 'none' 
      });
      return;
    }
    
    wx.request({
      url: `${serverUrl}/api/messages/read-all`,
      method: 'PUT',
      data: { userId },
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.hideLoading();
          wx.showToast({ title: '已全部标为已读' });
          
          // 更新本地消息状态
          const messages = this.data.messages.map(msg => {
            msg.isRead = true;
            return msg;
          });
          
          this.setData({ 
            messages,
            unreadCount: 0
          });
        } else {
          wx.hideLoading();
          wx.showToast({ 
            title: '操作失败', 
            icon: 'none' 
          });
        }
      },
      fail: (err) => {
        console.error('标记全部已读失败:', err);
        wx.hideLoading();
        wx.showToast({ 
          title: '操作失败', 
          icon: 'none' 
        });
        
        // 模拟成功
        const messages = this.data.messages.map(msg => {
          msg.isRead = true;
          return msg;
        });
        
        this.setData({ 
          messages,
          unreadCount: 0
        });
      }
    });
  }
});